import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcrypt';
import { createInterface } from 'readline';
import { generateSalt } from '../src/utils/crypto.js';

const prisma = new PrismaClient();

const rl = createInterface({
  input: process.stdin,
  output: process.stdout,
});

function question(query) {
  return new Promise(resolve => rl.question(query, resolve));
}

async function createAdmin() {
  try {
    console.log('\n=== 创建管理员账户 ===\n');
    
    // 检查是否已有管理员
    const adminCount = await prisma.user.count({
      where: { role: 'admin' },
    });
    
    if (adminCount > 0) {
      const proceed = await question(`系统中已有${adminCount}个管理员账户，是否继续创建？(y/N): `);
      if (proceed.toLowerCase() !== 'y') {
        console.log('已取消');
        process.exit(0);
      }
    }
    
    // 输入用户信息
    const username = await question('请输入用户名 (至少3个字符): ');
    if (username.length < 3) {
      throw new Error('用户名至少3个字符');
    }
    
    const email = await question('请输入邮箱: ');
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      throw new Error('邮箱格式不正确');
    }
    
    // 检查用户名和邮箱是否已存在
    const existing = await prisma.user.findFirst({
      where: {
        OR: [{ username }, { email }],
      },
    });
    
    if (existing) {
      throw new Error('用户名或邮箱已被使用');
    }
    
    const password = await question('请输入密码 (至少8个字符): ');
    if (password.length < 8) {
      throw new Error('密码至少8个字符');
    }
    
    const confirmPassword = await question('确认密码: ');
    if (password !== confirmPassword) {
      throw new Error('两次密码输入不一致');
    }
    
    console.log('\n正在创建管理员账户...');
    
    // 创建管理员
    const passwordHash = await bcrypt.hash(password, 10);
    const masterKeySalt = generateSalt();
    
    const admin = await prisma.user.create({
      data: {
        username,
        email,
        passwordHash,
        masterKeySalt,
        role: 'admin',
        isActive: true,
      },
    });
    
    // 创建默认偏好设置
    await prisma.userPreference.create({
      data: { userId: admin.id },
    });
    
    console.log('\n✓ 管理员账户创建成功！');
    console.log(`  用户名: ${username}`);
    console.log(`  邮箱: ${email}`);
    console.log(`  角色: 管理员`);
    console.log('\n请妥善保管您的密码！\n');
    
  } catch (error) {
    console.error('\n❌ 创建失败:', error.message);
    process.exit(1);
  } finally {
    rl.close();
    await prisma.$disconnect();
  }
}

createAdmin();


